<!--
 * @Author: licongwei
 * @Date: 2022-03-11 19:04:01
 * @FileDescription: 时间
-->
<template>
  <div class="clock">
    <p>{{ year }}</p>
    <p>{{ date }}</p>
    <p>{{ time }}</p>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, onBeforeUnmount } from 'vue'
interface IState {
  // eslint-disable-next-line no-undef
  timer: NodeJS.Timer | null
  year: string
  date: string
  time: string
  updateTime: () => void
  zeroPadding: (num: number, digit?: number) => string
}
export default defineComponent({
  name: 'clock',
  setup() {
    const state: IState = reactive({
      timer: null,
      year: '',
      date: '',
      time: '',
      updateTime: () => {
        let cd = new Date()
        state.year = `${state.zeroPadding(cd.getFullYear(), 4)}年`
        state.date = `${state.zeroPadding(
          cd.getMonth() + 1
        )}月${state.zeroPadding(cd.getDate())}日`
        state.time = `${state.zeroPadding(cd.getHours())}:${state.zeroPadding(
          cd.getMinutes()
        )}:${state.zeroPadding(cd.getSeconds())}`
      },
      zeroPadding: (num: number, digit = 2) => {
        let zero = ''
        for (let i = 0; i < digit; i++) {
          zero += '0'
        }
        return (zero + num).slice(-digit)
      }
    })
    state.updateTime()
    state.timer = setInterval(state.updateTime, 1000)
    onBeforeUnmount(() => {
      state.timer && clearInterval(state.timer)
    })
    return {
      ...toRefs(state)
    }
  }
})
</script>
<style lang="less" scoped>
.clock {
  position: absolute;
  top: 75px;
  left: 1600px;
  display: flex;
  p {
    font-size: 18px;
    font-family: 'AliHYAiHei';
    color: #31aaff;
    padding-right: 15px;
  }
}
</style>
